package cn.szzsi.interceptor;
import cn.szzsi._Config;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;

/**
 * 商户管理员的后台登录判断
 */
public class AdminInterceptor implements Interceptor {
    private String loginUrl = _Config.p.get("loginUrl");

	public void intercept(Invocation ai) {
	    Controller c = ai.getController();
        String _auth =c.getCookie("_auth");
        if(StrKit.isBlank(_auth)){
            c.renderHtml("<script>top.location.href='"+loginUrl+"';</script>");
            return;
        }
        if(!getUserInfo(_auth,c)){
            c.renderHtml("<script>top.location.href='"+loginUrl+"';</script>");
            return;
        }else{
            ai.invoke();
        }
	}

    public boolean getUserInfo(String _auth, Controller c) {
        if(StrKit.isBlank(_auth)){//
            return false;
        }
        String userInfo = this.getFromRedis(_auth);
        if(StrKit.isBlank(userInfo)) {
            return false;
        } else {
            JSONObject ui = JSONObject.parseObject(userInfo);
            String shopId;
            if("super".equals(ui.get("b_shoprank"))) {
                shopId = ui.getString("id");
            } else {
                shopId = ui.getString("b_shoprank");
            }

            c.setAttr("shopId", shopId);
            c.setAttr("userId", ui.getString("id"));
            c.setAttr("userName", ui.getString("username"));
            return true;
        }
    }

    /**
     * 根据_auth换取用户信息
     * @param _auth
     * @return
     */
    private String getFromRedis(String _auth){
	    String redis= Redis.use("zshop").get(_auth);
        return redis;
    }

}
